<template>
	<div class="table-demo-container layout-padding">
		<el-row>
			<el-col :xs="24" :sm="24">
				<el-card shadow="hover" header="实验检索">
					<TableSearch :search="state.search" @search="onSearch" ref="searchRef" />
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="24">
				<el-card shadow="hover" class="group-card">
					<template #header>
						<span>学生分组</span>
						<el-button size="default" type="success" class="ml10" @click="onAddGroupRow" :disabled="isButtonDisabled">
							<el-icon>
								<ele-FolderAdd />
							</el-icon>
							新增分组
						</el-button>
						<el-upload
							accept=".xlsx, .xls"
							:show-file-list="false"
							:limit="1"
							class="group-card-upload"
							ref="upload"
							action="#"
							:auto-upload="false"
							:on-change="handleChange"
							:disabled="isButtonDisabled"
						>
							<template #trigger>
								<el-button size="default" type="primary" class="ml10" :disabled="isButtonDisabled">
									<el-icon>
										<ele-FolderOpened />
									</el-icon>
									选择Excel文件
								</el-button>
							</template>
							<el-button
								style="margin-top: -8px"
								size="default"
								type="success"
								class="ml10"
								@click="onSubmit"
								:disabled="isButtonDisabled"
								v-loading.fullscreen.lock="fullscreenLoading"
								:element-loading-text="'数据加载中,请稍后...'"
							>
								<el-icon>
									<ele-DocumentChecked />
								</el-icon>
								提交
							</el-button>
						</el-upload>
					</template>
					<div v-show="groupList.length == 0">
						<el-empty description="暂无数据" />
					</div>
					<el-row :gutter="35" v-for="(v, k) in groupList" :key="k" v-show="groupList.length != 0">
						<el-button type="danger" circle size="small" @click="onDelGroupRow(k)" class="delete-group-button">
							<el-icon>
								<ele-Delete />
							</el-icon>
						</el-button>
						<el-cow :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
							<el-card class="card" shadow="hover">
								<template #header>
									<span>{{ v.name }}</span>
									<el-button size="default" type="success" class="ml10" @click="openAddStudentDialog(k)">
										<el-icon>
											<ele-FolderAdd />
										</el-icon>
										新增学生
									</el-button>
								</template>
								<el-empty class="empty" image-size="100" description="暂无数据" v-show="v.value.length == 0" />
								<el-row :gutter="40" style="overflow: hidden">
									<el-col
										v-for="(item, key) in v.value"
										:key="key"
										v-show="v.value.length != 0"
										:xs="12"
										:sm="6"
										:md="4"
										:lg="4"
										:xl="3"
										class="mb20"
									>
										<el-button type="danger" circle size="small" @click="onDelStudentRow(k, key)" class="delete-student-button">
											<el-icon>
												<ele-Delete />
											</el-icon>
										</el-button>
										<el-card class="student-card">
											<template #header>
												<el-tooltip :content="item['姓名']" placement="top" effect="dark">
													<div class="title-wrapper">
														{{ item['姓名'] }}
													</div>
												</el-tooltip>
											</template>
											<ele-Avatar class="avatar" />
										</el-card>
									</el-col>
								</el-row>
							</el-card>
						</el-cow>
					</el-row>
				</el-card>
			</el-col>
		</el-row>
		<Dialog ref="DialogRef" @student="getStudent" :dialog="info"></Dialog>
	</div>
</template>

<script setup lang="ts" name="studentGroup">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getStudentInfo, addGroupInfo, addGradeInfo } from '/@/api/student/group';
import * as XLSX from 'xlsx';

// 引入组件
const TableSearch = defineAsyncComponent(() => import('/@/views/student/group/search.vue'));
const Dialog = defineAsyncComponent(() => import('/@/views/student/group/dialog.vue'));

// 定义变量内容
const upload = ref(null);
const groupList = ref<Array<EmptyObjectType>>([]);
const DialogRef = ref();
const count = ref(0);
const index = ref(-1);
const fullscreenLoading = ref(false);
const experiment_id = ref('');
const isButtonDisabled = ref(true);
const studentList = ref([]);
const searchRef = ref(null);
const info = ref<EmptyObjectType>([]);
const state = reactive<gradeTableType>({
	search: [
		{ label: '实验编号', prop: 'id', placeholder: '请输入实验编号', required: true, type: 'input' },
		{ label: '小组人数', prop: 'count', placeholder: '请输入小组人数', required: true, type: 'input' },
	],
});

const onSearch = (data: EmptyObjectType) => {
	count.value = Number(data.count);
	isButtonDisabled.value = false;
	info.value = data;
	experiment_id.value = data.id;
};

const handleChange = (file: any) => {
	const reader = new FileReader();
	reader.onload = (e) => {
		const data = new Uint8Array(e.target?.result as any);
		const workbook = XLSX.read(data, { type: 'array' });
		const sheetName = workbook.SheetNames[0];
		const worksheet = workbook.Sheets[sheetName];
		const jsonData = XLSX.utils.sheet_to_json(worksheet);
		for (let i = 0; i < jsonData.length; i += count.value) {
			groupList.value.push({
				key: Math.floor(i / count.value),
				name: `第${Math.floor(i / count.value) + 1}组`,
				value: jsonData.slice(i, i + count.value),
			});
		}
	};
	reader.readAsArrayBuffer(file.raw);
};

//提交分组
const onSubmit = () => {
	fullscreenLoading.value = true;
	setTimeout(() => {
		for (let i = 0; i < groupList.value.length; i++) {
			addGroupInfo({
				experiment_id: experiment_id.value,
				group_name: groupList.value[i].name,
			})
				.then((res) => {
					if (res.code === '2000') {
						for (let j = 0; j < groupList.value[i].value.length; j++) {
							for (let k = 0; k < groupList.value[i].value.length; k++) {
								if (groupList.value[i].value[j]['学号'] != groupList.value[i].value[k]['学号']) {
									addGradeInfo({
										group_id: res.data.group_id,
										experiment_id: res.data.experiment_id,
										evaluatee_id: groupList.value[i].value[j]['学号'],
										evaluator_id: groupList.value[i].value[k]['学号'],
										evaluated_grade: -1,
									})
										.then((result) => {
											if (result.code === '2000') {
												groupList.value = [];
												if (searchRef.value) {
													searchRef.value.clearFormData();
												}
												fullscreenLoading.value = false;
											} else {
												ElMessage.error('分组成绩添加失败!');
												fullscreenLoading.value = false;
											}
										})
										.catch((error) => {
											ElMessage.error('分组成绩添加失败!' + error);
											fullscreenLoading.value = false;
										});
								}
							}
						}
					} else {
						ElMessage.error('分组提交失败!');
						fullscreenLoading.value = false;
					}
				})
				.catch((err) => {
					ElMessage.error('分组提交失败!' + err);
					fullscreenLoading.value = false;
				});
		}
	}, 2000);
};

//新增分组
const onAddGroupRow = () => {
	groupList.value.push({ key: groupList.value.length, name: `第${groupList.value.length + 1}组`, value: [] });
	ElMessage.success('新增分组成功');
};

//新增学生
const openAddStudentDialog = (k: number) => {
	DialogRef.value.openDialog(groupList.value[k].value.map((item) => parseInt(item['学号']) || 0));
	index.value = k;
};

//删除分组
const onDelGroupRow = (k: number) => {
	groupList.value = groupList.value.filter((item) => item.key != k);
	for (let i = k; i < groupList.value.length; i++) {
		const number = parseInt(groupList.value[i].name.replace(/\D/g, ''), 10) || 0;
		groupList.value[i].name = `第${number - 1}组`;
	}
	ElMessage.success('删除分组成功');
};

//删除学生
const onDelStudentRow = (k: number, key: number) => {
	groupList.value[k].value.splice(key, 1);
	if (groupList.value[k].value.length == 0) {
		onDelGroupRow(k);
	}
};

const getStudent = (data: any) => {
	if (data == 'error') {
		isButtonDisabled.value = true;
		ElMessage.error('请输入正确的实验编号!');
	} else {
		const array = data.map(String);
		for (const item in array) {
			for (let i = 0; i < groupList.value.length; i++) {
				if (i != index.value) {
					for (const items in groupList.value[i].value) {
						if (groupList.value[i].value[items]['学号'] == array[item]) {
							onDelStudentRow(i, items['学号']);
						}
					}
				}
			}
			getStudentInfo(array[item])
				.then((res) => {
					if (res.code === '2000') {
						const studentArrary = res.data.map((item: any) => {
							return {
								学号: item.student_id,
								姓名: item.student_name,
							};
						});
						studentList.value.push(studentArrary[0]);
					} else {
						ElMessage.error('获取学生信息失败!');
					}
				})
				.catch((err) => {
					ElMessage.error('更新学生信息失败!' + err);
				});
		}
		groupList.value[index.value].value = studentList.value;
	}
};

onMounted(() => {
	groupList.value = [];
});
</script>

<style scoped lang="scss">
.table-demo-container {
	.table-demo-padding {
		padding: 15px;
		.table-demo {
			flex: 1;
			overflow: hidden;
		}
	}
}
.group-card {
	height: 500px;
	overflow: auto;
}
.group-card-upload {
	float: right;
	margin-right: 800px;
}

.delete-student-button {
	margin-top: 40px;
}

.card {
	height: 250px;
	width: 1200px;
	margin-left: 10px;
	overflow: hidden;
}

.empty {
	margin-top: -50px;
}
.delete-group-button {
	margin-top: 100px;
}

.student-card {
	height: 130px;
	width: 130px;
	float: right;
	text-align: center;
}
.avatar {
	height: 50px;
	width: 50px;
}

.title-wrapper {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	max-width: 100px;
}
</style>
